package com.ndood.admin.service.system.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ndood.admin.pojo.system.DepartmentPo;
import com.ndood.admin.pojo.system.dto.DepartmentDto;
import com.ndood.admin.pojo.system.dto.TreeDto;
import com.ndood.admin.repository.system.DepartmentRepository;
import com.ndood.admin.repository.system.manager.DepartmentRepositoryManager;
import com.ndood.admin.service.system.SystemDepartmentService;
import com.ndood.core.utils.JPAUtil;

/**
 * 部门模块业务类
 * @author ndood
 */
@Transactional
@Service
public class SystemDepartmentServiceImpl implements SystemDepartmentService {
	
	@Autowired
	private DepartmentRepository departmentDao;

	@Autowired
	private DepartmentRepositoryManager departmentRepositoryManager;
	
	@Override
	public List<DepartmentDto> getDepartmentList() throws Exception {
		return departmentRepositoryManager.getDepartmentList();
	}

	@Override
	public void batchDeleteDepartment(Integer[] ids) {
		for (Integer id : ids) {
			departmentDao.deleteById(id);
		}
	}

	@Override
	public DepartmentDto addDepartment(DepartmentDto dto) throws Exception {
		// Step1: 补充相关字段
		dto.setCreateTime(new Date());
		dto.setUpdateTime(new Date());
		DepartmentPo po = new DepartmentPo();
		
		// Step2: 处理上级部门
		Integer parentId = dto.getParentId();
		if (parentId != null) {
			DepartmentPo parent = departmentDao.findById(parentId).get();
			po.setParent(parent);
		}

		// Step3: 保存并返回
		JPAUtil.childToFather(dto, po);
		po = departmentDao.save(po);
		dto.setId(po.getId());
		return dto;
	}

	@Override
	public DepartmentDto getDepartment(Integer id) throws Exception {
		// Step1: 获取部门信息
		DepartmentDto dto = new DepartmentDto();
		DepartmentPo po = departmentDao.findById(id).get();
		JPAUtil.fatherToChild(po, dto);
		dto.setParent(po.getParent());
		return dto;
	}

	@Override
	public DepartmentDto updateDepartment(DepartmentDto dto) throws Exception {
		// Step1: 更新部门信息
		dto.setUpdateTime(new Date());
		DepartmentPo po = departmentDao.findById(dto.getId()).get();
		JPAUtil.childToFather(dto, po);
		departmentDao.save(po);
		
		// Step2: 获取隐含属性用于异步回显
		JPAUtil.fatherToChild(po, dto);
		return dto;
	}

	@Override
	public List<TreeDto> getDepartmentTree() {
		List<DepartmentPo> poList = departmentDao.findByOrderBySort();
		List<TreeDto> dtoList = new ArrayList<TreeDto>();
		for (DepartmentPo po : poList) {
			TreeDto dto = new TreeDto();
			dto.setId(po.getId());
			String pid = po.getParent() == null ? "#" : po.getParent().getId()+"";
			dto.setParent(pid);
			dto.setText(po.getName());
			dto.setType("menu");
			Map<String,Object> state = new HashMap<String,Object>();
			state.put("selected", false);
			dto.setState(state);
			dtoList.add(dto);
		}
		return dtoList;
	}
}
